from fastapi import APIRouter, Depends, HTTPException, status
from datetime import timedelta
from app.auth.auth_service import auth_service
from app.auth.dependencies import get_current_active_user, verify_role
from app.auth.models import User, UserCreate, UserInDB, Token, TokenData

router = APIRouter()

@router.post("/token", response_model=Token)
async def login_for_access_token(form_data: dict):
    """登录获取访问令牌"""
    user = auth_service.authenticate_user(form_data.get("username"), form_data.get("password"))
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=auth_service.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = auth_service.create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

@router.post("/users/", response_model=User)
async def create_user(user: UserCreate, current_user: User = Depends(verify_role("admin"))):
    """创建新用户（仅管理员）"""
    # 检查用户是否已存在
    existing_user = auth_service.get_user(user.username)
    if existing_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 创建新用户
    user_data = user.dict()
    created_user = auth_service.create_user(user_data)
    if not created_user:
        raise HTTPException(status_code=400, detail="创建用户失败")
    
    return created_user

@router.get("/users/me/", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
    """获取当前用户信息"""
    return current_user

@router.get("/users/{username}", response_model=User)
async def read_user(username: str, current_user: User = Depends(get_current_active_user)):
    """获取指定用户信息"""
    user = auth_service.get_user(username)
    if user is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user